import time

from fastapi import APIRouter, Depends, BackgroundTasks
from fastapi_amis_admin.globals.deps import AsyncSess, SyncSess
from fastapi_permissions.example import Item

from .models import SysUser, UserQueryParams
from .service import UserService as userService
from ..common import ApiResult, CommonUtil
from ..security.service import *

router = APIRouter()


@router.post("/permissions")
def permissions(userId:int, sess:SyncSess):
    list = userService.get_permissions(userId, sess)
    return ApiResult(data=list)

@router.post("/page")
def page(params: UserQueryParams, sess: SyncSess,
         item: Item = Permission("sys:user:page", get_principals)):
    return userService.page(params, sess)


@router.get("/detail", response_model=ApiResult)
def detail(id: int, sess: SyncSess,
           item: Item = Permission("sys:user:info", get_principals)):
    return ApiResult(data=userService.detail(id, sess))

@router.post("/save")
def save(sess: SyncSess, data: SysUser, cur_user = Depends(get_current_user),
         item: Item = Permission("sys:user:save", get_principals)):
    CommonUtil.add_common_field_set(data=data, userId=cur_user.id)
    userService.save(sess, data)
    return ApiResult()


@router.put("/update")
def update(data: SysUser, sess: SyncSess, cur_user = Depends(get_current_user),
           item: Item = Permission("sys:user:update", get_principals)):
    CommonUtil.update_common_field_set(data=data, userId=cur_user.id)
    userService.update(data, sess)
    return ApiResult()


@router.delete("/delete")
def delete(id: int, sess: SyncSess,
           item: Item = Permission("sys:user:delete", get_principals)):
    userService.delete(id, sess)
    return ApiResult()

def back_log(message: str):
    time.sleep(3)
    print(f"# back_log: {message}")

@router.get("/back_task", response_model=ApiResult)
def detail1(message: str, backTask: BackgroundTasks):
    backTask.add_task(back_log, message)
    return ApiResult(data=message)


@router.get("/test_sync_db", summary="测试同步数据库操作")
def test_sync_db(sess: SyncSess):
    # obj=sess.get(...)
    # do something
    pass


@router.get("/test_async_db", summary="测试异步数据库操作")
async def test_async_db(sess: AsyncSess):
    # obj=await sess.get(...)
    # do something
    pass

